package com.woniu.car.controller;

import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.car.common.ResponseEntity;
import com.woniu.car.dto.*;
import com.woniu.car.dto.constant.CommonConstant;
import com.woniu.car.entity.TServerDetail;
import com.woniu.car.entity.TServerOrder;
import com.woniu.car.exception.ParamException;
import com.woniu.car.exception.ServiceSException;
import com.woniu.car.mapper.TServerOrderMapper;
import com.woniu.car.param.DetailQueryParam;
import com.woniu.car.param.OrderDetailParam;
import com.woniu.car.service.TProcessValueService;
import com.woniu.car.service.TServerDetailService;
import com.woniu.car.service.TServerOrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName OrderController
 * @Description 订单业务
 * @Author 李磊
 * @Version 1.0
 **/
@RestController
@RequestMapping("/order")
@Api(tags = "订单模块")
@Slf4j
public class OrderController {

    @Resource
    private TServerOrderService tServerOrderService;
    @Resource
    private TServerDetailService tServerDetailService;
    @Resource
    private TProcessValueService tProcessValueService;
    @Resource
    private TServerOrderMapper tServerOrderMapper;

    @PostMapping("/insert")
    @ApiOperation("商家服务下单(订单和订单详情新增)")
    @ApiImplicitParam(name = "ListDetailParam", value = "订单详情参数")
    public ResponseEntity insert(@Validated @RequestBody List<OrderDetailParam> orderDetailList, @RequestHeader("id") Integer id) throws InterruptedException {

        ServerOrderDto serverOrderDto = tServerOrderService.insertOrder(orderDetailList, id);
        Integer orderId = serverOrderDto.getOrderId();

        return new ResponseEntity(ResponseCodeDto.SUCCESS.getCode(),
                ResponseCodeDto.SUCCESS.getMessage(),
                serverOrderDto);
    }

    @GetMapping("/pay")
    @ApiOperation("支付宝")
    public String aliPay(String subject, String orderName, String total) throws Exception {

        if (null == subject || null == orderName || null == total) {
            throw new ParamException(CommonConstant.PROCESSNULL);
        }

        try {
            double v = Double.parseDouble(total);
        } catch (Exception e) {
            throw new ParamException(CommonConstant.TOTALWRONG);
        }

        AlipayTradePagePayResponse pay = Factory.Payment.Page().pay(subject, orderName, total, "www.woniuxy.com");
        return pay.getBody();
    }

    /**
    *@Author 李磊
    *@Description 用户订单查询
    *@Param [userId]
    *@return com.woniu.car.common.ResponseEntity
    **/
    @ApiOperation("用户订单查询")
    @GetMapping("/queryOrder")
    public ResponseEntity queryOrder(Integer userId,Integer pageNum, Integer pageSize){

        if (null == userId || userId <= 0) {
            throw new ParamException(CommonConstant.COMMENTQUERYWRONG);
        }

        Page<TServerOrder> page = new Page<>(pageNum,pageSize);

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id",userId);
        Page page1 = tServerOrderMapper.selectPage(page, wrapper);

        List<TServerOrder> list = page1.getRecords();
        System.out.println(list);

        List<ServerOrderDto> serverOrderDtos = new ArrayList<>();

        for (TServerOrder tServerOrder : list) {
            ServerOrderDto serverOrderDto = new ServerOrderDto();
            BeanUtils.copyProperties(tServerOrder,serverOrderDto);
            serverOrderDtos.add(serverOrderDto);
        }

        return new ResponseEntity(ResponseCodeDto.SUCCESS.getCode(),
                ResponseCodeDto.SUCCESS.getMessage(),
                serverOrderDtos);
    }

    /**
    *@Author 李磊
    *@Description 用户订单详情查询
    *@Param [orderId, id]
    *@return com.woniu.car.common.ResponseEntity
    **/
    @ApiOperation("用户订单详情查询")
    @GetMapping("/queryDetail")
    public ResponseEntity queryDetail(Integer orderId, @RequestHeader("id") Integer id){

        TServerOrder byId = tServerOrderService.getById(id);
        if (null == byId) {
            throw new ParamException(CommonConstant.DETAILWRONG);
        }

        QueryWrapper wrapper = new QueryWrapper();
        if (null != orderId) {
            wrapper.eq("order_id",orderId);
            if (orderId <= 0) {
                throw new ParamException(CommonConstant.COMMENTQUERYWRONG);
            }
        }

        List<TServerDetail> list = tServerDetailService.list(wrapper);

        if (null == list || list.size() <= 0) {
            throw new ParamException(CommonConstant.RESULTNULL);
        }

        List<ServiceDetailDto> serviceDetailDtos = new ArrayList<>();
        for (TServerDetail tServerDetail : list) {
            ServiceDetailDto detailDto = new ServiceDetailDto();
            BeanUtils.copyProperties(tServerDetail,detailDto);
            serviceDetailDtos.add(detailDto);
        }

        return new ResponseEntity(ResponseCodeDto.SUCCESS.getCode(),
                ResponseCodeDto.SUCCESS.getMessage(),
                serviceDetailDtos);
    }


    /**
     *@Author 李磊
     *@Description 商家订单详情查询
     *@Param [orderId, id]
     *@return com.woniu.car.common.ResponseEntity
     **/
    @ApiOperation("商家订单详情查询（已处理订单、未处理订单或所有订单）")
    @GetMapping("/queryDetailByStatus")
    public ResponseEntity<List<ServiceDetailDto>> queryDetailByStatus(DetailQueryParam detailQueryParam) throws ServiceSException {

        if (null == detailQueryParam) {
            throw new ParamException(CommonConstant.PROCESSNULL);
        }

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("shop_id",detailQueryParam.getShopId());
        wrapper.eq("status",detailQueryParam.getStatus());

        if (null != detailQueryParam.getStartTime()) {
            wrapper.gt("create_time",detailQueryParam.getStartTime());
        }
        if (null != detailQueryParam.getEndTime()) {
            wrapper.lt("create_time",detailQueryParam.getEndTime());
        }

        List<TServerDetail> list = tServerDetailService.list(wrapper);

        if (null == list || list.size() <= 0) {
            throw new ServiceSException(CommonConstant.RESULTNULL);
        }

        List<ServiceDetailDto> serviceDetailDtos = new ArrayList<>();
        for (TServerDetail tServerDetail : list) {
            ServiceDetailDto serviceDetailDto = new ServiceDetailDto();
            BeanUtils.copyProperties(tServerDetail,serviceDetailDto);
            serviceDetailDtos.add(serviceDetailDto);
        }

        return new ResponseEntity<List<ServiceDetailDto>>(ResponseCodeDto.SUCCESS.getCode(),
                ResponseCodeDto.SUCCESS.getMessage(),
                serviceDetailDtos);
    }

    /**
    *@Author 李磊
    *@Description 修改订单详情状态（店内消费）
    *@Param [qrCode]
    *@return com.woniu.car.common.ResponseEntity
    **/
    @ApiOperation("修改订单详情状态（店内消费）")
    @PutMapping("/updateDetail")
    public ResponseEntity updateDetail(String qrCode) throws Exception {

        if (null == qrCode) {
            throw new ParamException(CommonConstant.RESULTNULL);
        }

        QueryWrapper wrapper1 = new QueryWrapper();
        wrapper1.eq("qr_code",qrCode);
        TServerDetail one = tServerDetailService.getOne(wrapper1);

        if (null == one) {
            throw new ParamException(CommonConstant.QRWRONG);
        }

        Integer detailId = one.getDetailId();

        TServerOrder byId = tServerOrderService.getById(one.getOrderId());
        Integer userId = byId.getUserId();


        if (CommonConstant.ONE.equals(one.getStatus())) {
            throw new ParamException(CommonConstant.USERED);
        }

        TServerDetail detail = new TServerDetail();
        detail.setDetailId(detailId);
        detail.setStatus(CommonConstant.ONE);
        boolean update = tServerDetailService.updateById(detail);

        if (!update) {
            throw new ServiceSException(CommonConstant.UPDATEERROR);
        }

        //生成服务流程
        List<TProcessValueDto> tProcessValueDtos = tProcessValueService.insertValue(one.getDetailId(), userId);

        return new ResponseEntity(ResponseCodeDto.SUCCESS.getCode(),
                ResponseCodeDto.SUCCESS.getMessage(),
                tProcessValueDtos);
    }

    /**
    *@Author 李磊
    *@Description 付款成功后更新订单详情状态，生成消费码
    *@Param [orderId]
    *@return com.woniu.car.common.ResponseEntity
    **/
    @ApiOperation("付款成功后更新订单详情状态，生成消费码")
    @PutMapping("/updateAfterPay")
    public ResponseEntity updateAfterPay(Integer orderId) throws Exception {

        List<ServiceDetailDto> serviceDetailDtos = tServerDetailService.updateAfterPay(orderId);

        return new ResponseEntity(ResponseCodeDto.SUCCESS.getCode(),
                ResponseCodeDto.SUCCESS.getMessage(),
                serviceDetailDtos);
    }

}
